package cn.actoncode.boot.module.ai.dal.redis.no;

import cn.actoncode.boot.framework.common.util.date.DateUtils;
import cn.actoncode.boot.module.ai.dal.redis.RedisKeyConstants;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import jakarta.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 唯一编号 redis
 * @author bin
 **/
@Repository
public class UniqueNoRedisDAO {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Long incr(String date) {
        String redisKey = formatKey(date);
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(redisKey))) {
            return stringRedisTemplate.opsForValue().increment(redisKey);
        } else {
            Long incr = stringRedisTemplate.opsForValue().increment(redisKey, RandomUtils.nextInt(1000, 1999));
            // 获取过期时间 单位:豪秒
            Date day = DateUtils.getNextDay();
            long timeout = day.getTime() - System.currentTimeMillis();
            stringRedisTemplate.expire(redisKey, timeout, TimeUnit.MILLISECONDS);
            return incr;
        }
    }

    public Long incr(String date, long delta) {
        String redisKey = formatKey(date);
        return stringRedisTemplate.opsForValue().increment(redisKey, delta);
    }

    private static String formatKey(String date) {
        return String.format(RedisKeyConstants.UNIQUE_NO, date);
    }
}
